package com.kejizhentan.springboot2thymeleaf.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 */
@Controller
@Slf4j
public class FormController {
    @GetMapping("/form_layouts")
    public String form_layouts(){
        return "form/form_layouts";
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headImg") MultipartFile headImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {
        log.info("上传的信息：email={}，username={}，headImg={}，photos={}",email,username,headImg.getSize(),photos.length);
        if(headImg != null){
            //保存到文件服务器或者oss服务器
            String headImgName = headImg.getOriginalFilename();//获取文件的原始文件名
            headImg.transferTo(new File("D:\\test\\"+headImgName));
        }
        if(photos != null && photos.length > 0){
            for (MultipartFile photo : photos) {
                if(photo != null){
                    String photoImgName = photo.getOriginalFilename();//获取文件的原始文件名
                    photo.transferTo(new File("D:\\test\\"+photoImgName));
                }
            }
        }
        return "main";
    }
}
